﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ElingOA6_Admin_DSJCJ.Common;
using System.Data;
using Newtonsoft.Json;
using ElingOA6_Admin_DSJCJ.Areas.Admin.Models;
using DevExpress.Web.Mvc;

namespace ElingOA6_Admin_DSJCJ.Areas.Admin.Controllers
{
    /// <summary>
    /// JCMS信息推送
    /// </summary>
    [OutputCache(Duration = 0, VaryByParam = "none")]
    public class JcmsPushToController : AdminBaseController
    {
        //
        // GET: /Admin/JcmsPushTo/

        /// <summary>
        /// 信息类别逻辑类
        /// </summary>
        private BLL.DocCls docClsBLL = new BLL.DocCls();
        /// <summary>
        /// 通用方法逻辑类
        /// </summary>
        private BLL.Common commonBLL = new BLL.Common();
        /// <summary>
        /// 文档逻辑类
        /// </summary>
        private BLL.Document documentBLL = new BLL.Document();
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            return View();
        }
        /// <summary>
        /// 文档列表
        /// </summary>
        /// <returns></returns>
        public ActionResult DocumentList(string docClsCd = "", int id = 1)
        {
            string entityNo = GlobalConstant.ENTITYNO;
            ActionResult actionResult = null;
            Model.DocCls docClsModel = new Model.DocCls();
            string tableName = "";

            if (docClsCd == "")
            {
                tableName = "dbo.fn_GetJcmsDocumentALLByCTE('" + entityNo + "')";
            }
            else
            {
                docClsCd = Fetch.InspectData(docClsCd, CheckGetEnum.Safety);
                if (docClsCd != "")
                {
                    docClsModel = docClsBLL.GetModel(entityNo, docClsCd);
                    if (docClsModel != null)
                    {
                        tableName = "dbo.fn_GetJcmsDocumentByCTE('" + docClsCd + "','" + entityNo + "')";

                    }
                }
            }
            int pageRowSize = 15;
            int pageIndex = id;
            ViewData["pageIndex"] = id - 1;

            string fiedls = "*";
            int total;
            //初始化查询条件
            Models.DocQueryConditionModel conditionModel = new DocQueryConditionModel();
            string emplNo = OperateSession.get(GlobalConstant.PARAM_FEMPLNO);
            string queryWhere = "FRecycle='N' AND FIsEnroll='Y' AND FIsPubJCMS='N' ";//默认为未推送
            ViewData["docQueryCondition"] = JsonConvert.SerializeObject(conditionModel);
            queryWhere += " AND FIsReference='N'";
            DataSet ds = commonBLL.GetListByPage(tableName, fiedls, pageRowSize, pageIndex, queryWhere, "FIsTop desc,FTopSeq asc,FPubDate", 1, out total);
            List<DocumentGridModel> documentAllList = new List<DocumentGridModel>();
            List<DocumentGridModel> documentList = ViewDataRowToModel.DataTableToListDocuemt(ds.Tables[0]);

            for (int i = 0; i < total; i++)
            {
                documentAllList.Add(null);
            }
            for (int i = 0; i < pageRowSize; i++)
            {
                if (documentList.Count > i)
                {
                    documentAllList[((pageIndex - 1) * pageRowSize) + i] = documentList[i];
                }
            }
            if (docClsCd == "")
            {
                ViewData["docClsPathName"] = "全部类别";
            }
            else
            {
                ViewData["docClsPathName"] = docClsBLL.GetDocClsPathNames(entityNo, docClsCd);
            }
            DocumentListViewModel documentListVewModel = new DocumentListViewModel(docClsModel, documentAllList);



            actionResult = View("DocumentList", documentListVewModel);
            return actionResult;
        }

        /// <summary>
        /// 文档列表翻页操作
        /// </summary>
        /// <returns>视图</returns>
        public ActionResult DocumentListPartial()
        {
            int pageIndex = Request.Params["pageIndex"] == null ? 0 : int.Parse(Request.Params["pageIndex"].ToString());
            int pageCount = Request.Params["PageCount"] == null ? 0 : int.Parse(Request.Params["PageCount"].ToString());
            int pageRowSize = Request.Params["pageRowSize"] == null ? 0 : int.Parse(Request.Params["pageRowSize"].ToString());
            int pageRowCount = Request.Params["pageRowCount"] == null ? 0 : int.Parse(Request.Params["pageRowCount"].ToString());

            string docClsCd = Request.Params["docClsCd"];
            string callbackArg = DevExpressHelper.CallbackArgument;
            string command = Request.Params["command"] == null ? "" : Request.Params["command"].ToString();

            if (command == "PAGERONCLICK")
            {
                string[] args = callbackArg.Split(new char[1] { '|' });
                string arg = args[args.Count() - 1];

                switch (arg)
                {
                    case "PBN;":
                        {
                            //下一页
                            pageIndex = pageIndex + 2;
                            break;
                        }
                    case "PBP;":
                        {
                            //上一页
                            //pageIndex = pageIndex;
                            break;
                        }
                    case "PBL;":
                        {
                            //最后一页
                            pageIndex = pageCount;
                            break;
                        }
                    case "PBF;":
                        {
                            //第一页
                            pageIndex = 1;
                            break;
                        }
                    default:
                        {
                            //点击数字页码
                            string tempIndex = arg.Replace("PN", "");
                            tempIndex = tempIndex.Replace(";", "");
                            if (RegExp.IsNumeric(tempIndex))
                            {
                                pageIndex = int.Parse(tempIndex) + 1;
                            }
                            break;
                        }

                }
            }
            else
            {
                if (command == "REFRESH")
                {
                    //第一页
                    pageIndex = 1;
                }
                else
                {
                    pageIndex = pageIndex + 1;
                }
            }

            string entityNo = GlobalConstant.ENTITYNO;

            ViewData["pageIndex"] = pageIndex - 1;

            string fiedls = "*";
            int total;
            Model.DocCls docClsModel = new Model.DocCls();
            string tableName = "";
            if (docClsCd == "")
            {
                tableName = "dbo.fn_GetJcmsDocumentALLByCTE('" + entityNo + "')";
            }
            else
            {
                docClsCd = Fetch.InspectData(docClsCd, CheckGetEnum.Safety);
                if (docClsCd != "")
                {
                    docClsModel = docClsBLL.GetModel(entityNo, docClsCd);
                    if (docClsModel != null)
                    {
                        tableName = "dbo.fn_GetJcmsDocumentByCTE('" + docClsCd + "','" + entityNo + "')";
                    }
                }
            }
            ViewData["isAuthority"] = false;
            ViewData["isInportEaccount"] = false;

            //查询条件
            string conditionString = Request.Params["queryCondition"].ToString();

            string queryWhere = " FRecycle='N' AND FIsEnroll='Y'";
            if (conditionString != "")
            {
                Models.DocQueryConditionModel conditionModel = JsonConvert.DeserializeObject<Models.DocQueryConditionModel>(conditionString);
                if (!string.IsNullOrEmpty(conditionModel.FStatus))
                {
                    queryWhere += " AND FIsPubJCMS='" + Fetch.InspectData(conditionModel.FStatus, CheckGetEnum.Safety) + "'";
                }

                if (!string.IsNullOrEmpty(conditionModel.FTitle))
                {
                    if (conditionModel.FTitle.Trim() != "")
                    {
                        queryWhere += " AND FTitle Like '%" + Fetch.InspectData(conditionModel.FTitle, CheckGetEnum.Safety) + "%'";
                    }
                }
                if (conditionModel.BeginPubDate.HasValue && conditionModel.EndPubDate.HasValue)
                {
                    queryWhere += " AND DATEDIFF(day,'" + conditionModel.BeginPubDate.Value + "',FPubDate)>=0 AND DATEDIFF(day,'" + conditionModel.EndPubDate.Value + "',FPubDate)<=0 ";
                }
                else
                {
                    if (conditionModel.BeginPubDate.HasValue)
                    {
                        queryWhere += " AND DATEDIFF(day,'" + conditionModel.BeginPubDate.Value + "',FPubDate)>=0";
                    }
                    else
                    {
                        if (conditionModel.EndPubDate.HasValue)
                        {
                            queryWhere += " AND  DATEDIFF(day,'" + conditionModel.EndPubDate.Value + "',FPubDate)<=0 ";

                        }
                    }
                }
                if (conditionModel.PubEmplList != null && conditionModel.PubEmplList.Count > 0)
                {
                    // 目前支持单用户选择
                    string emplNo = conditionModel.PubEmplList[0].Value;
                    queryWhere += " AND FEmplNo='" + emplNo + "'";
                }
                if (conditionModel.DeptList != null && conditionModel.DeptList.Count > 0)
                {
                    // 目前支持单部门选择
                    string queryDeptNo = conditionModel.DeptList[0].Value;
                    queryWhere += " AND FDeptNo='" + queryDeptNo + "'";
                }
                if (conditionModel.WorkGroupList != null && conditionModel.WorkGroupList.Count > 0)
                {
                    // 目前支持单部门选择
                    string workGrpNo = conditionModel.WorkGroupList[0].Value;
                    queryWhere += " AND FWorkGrpNo='" + workGrpNo + "'";
                }
            }
            queryWhere += " AND FIsReference='N'";
            DataSet ds = commonBLL.GetListByPage(tableName, fiedls, pageRowSize, pageIndex, queryWhere, "FIsTop desc,FTopSeq asc,FPubDate", 1, out total);
            List<DocumentGridModel> documentAllList = new List<DocumentGridModel>();
            List<DocumentGridModel> documentList = ViewDataRowToModel.DataTableToListDocuemt(ds.Tables[0]);

            for (int i = 0; i < total; i++)
            {
                documentAllList.Add(null);
            }
            for (int i = 0; i < pageRowSize; i++)
            {
                if (documentList.Count > i)
                {
                    documentAllList[((pageIndex - 1) * pageRowSize) + i] = documentList[i];
                }
            }
            DocumentListViewModel documentListVewModel = new DocumentListViewModel(docClsModel, documentAllList);
            if (docClsCd == "")
            {
                ViewData["docClsPathName"] = "全部类别";
            }
            else
            {
                ViewData["docClsPathName"] = docClsBLL.GetDocClsPathNames(entityNo, docClsCd);
            }
            return PartialView("DocumentListPartial", documentListVewModel);
        }
        /// <summary>
        /// 推送至JCMS
        /// </summary>
        /// <param name="docId"></param>
        /// <returns></returns>
        public string PushToJcms(decimal docId)
        {
            string jsonstr = "FAILED";
            string errorMessage = "错误";
            string entityNo = GlobalConstant.ENTITYNO;

            Model.Document docModel = documentBLL.GetModel(docId);
            if (docModel != null)
            {

                Model.DocCls docClsModel = docClsBLL.GetModel(entityNo, docModel.FDocClsCd);
                if (docClsModel != null)
                {
                    if (docClsModel.FJCMSColID.HasValue)
                    {

                        try
                        {
                            documentBLL.UpdateJcms(docId, "Y", docClsModel.FJCMSColID.Value.ToString());
                            Common.GenerateUtil.PulishToJcms(docModel, docModel.FDocClsCd);
                            jsonstr = "SUCCESS";
                        }
                        catch (Exception ee)
                        {
                            errorMessage = "推送错误" + ee.Message;
                        }
                    }
                    else
                    {
                        errorMessage = "信息类别的对应JCMS编号未定义";
                    }

                }
                else
                {
                    errorMessage = "对应信息类别不存在";
                }

            }
            else
            {
                errorMessage = "对应信息不存在";
            }

            if (jsonstr == "FAILED")
            {
                jsonstr += "FAILED|" + errorMessage;
            }
            return jsonstr;
        }
    }
}
